package net.zjitc.service.impl;

import net.zjitc.mapper.CategoryMapper;
import net.zjitc.pojo.Category;
import net.zjitc.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    @Cacheable(value = "categoryCache",key = "'list'")
    public List<Category> findAll() {
        List<Category> list = categoryMapper.findAll();
        return list;
    }

    @Override
    @Cacheable(value = "categoryCache", key = "#id", unless = "#result == null")
    public Category findOne(Integer id) {
        return categoryMapper.findOne(id);
    }


    @Override
    @Caching(
            put = @CachePut(value = "categoryCache", key = "#category.id"),
            evict = @CacheEvict(value = "categoryCache", key = "'list'"))
    public void update(Category category) {
        categoryMapper.update(category);
    }


    @Override
    @Caching(evict = {
            @CacheEvict(value = "categoryCache", key = "#id"),
            @CacheEvict(value = "categoryCache", key = "'list'") // 清除列表缓存
    })
    public void delete(Integer id) {
        categoryMapper.delete(id);
    }


    @Override
    @Caching(
            put = @CachePut(value = "categoryCache", key = "#category.id"), // 使用返回对象的ID
            evict = @CacheEvict(value = "categoryCache", key = "'list'")
    )
    public Category add(Category category) {
        categoryMapper.add(category);
        return categoryMapper.findOne(category.getId()); // 返回完整带ID的Category对象
    }



}